package util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtils{
	private static SqlSessionFactory factory = null;
	private static ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();
	static{
		// 1 读取配置文件 config.xml
		InputStream in = null;
		try {
			in = Resources.getResourceAsStream("mybatis-config.xml");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		// 2 创建SqlSessionFactory
		factory = new SqlSessionFactoryBuilder().build(in);
	}
	
	 public static SqlSession openSession(){
		// 3 创建SqlSession
		 SqlSession sqlSession = tl.get();
		 if(sqlSession == null){
			 sqlSession = factory.openSession();
			 tl.set(sqlSession);
		 }
	  return sqlSession;

	 }


	 public static void close(SqlSession sqlSession){

	   if(sqlSession != null){
		   tl.remove();
	     sqlSession.close();
	   }

	 }
	}
